<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="选位方案" :visible.sync="dialogShow" center top="100px" width="80%"
    @close="closeConfigDialog" :before-close="beforeClose" @opened="showDialog"
  >
    <div class="header">期望时间&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ dateRange[0] }}&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;{{
        dateRange[1]
      }}
    </div>
    <div class="search_box">
      <el-divider content-position="left">筛选点位</el-divider>
      <!--筛选条件-->
      <transition name="el-zoom-in-top">
        <div v-show="show">
          <el-form ref="searchForm" :model="searchForm" :rules="rules" :inline="true" size="mini">
            <div style="position: relative">
              <div class="search_card">
                <el-form-item label="行政规划" prop="pcaList" style="margin-left: 20px">
                  <el-select ref="adcode" v-model="searchForm.pcaList" clearable multiple placeholder="请选择">
                    <el-option
                      v-for="item in adcodes"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="地址" prop="address" class="no-first-el-form-item">
                  <el-input v-model.trim="searchForm.address" placeholder="请输入地址" clearable style="width: 400px">
                    <el-button slot="append" icon="el-icon-search" @click="getLocation"/>
                  </el-input>
                  <div v-show="searchForm.positionLocationList.length>0" style="width: 400px;padding: 5px">
                    <el-tag v-for="(item,index) in searchForm.positionLocationList" :key="item.id" type="primary"
                            size="mini"
                            :closable="true"
                            style="margin: 2px" @close="handleClose(index)"
                    >{{ item.title }}
                    </el-tag>
                  </div>
                </el-form-item>
                <el-form-item label="辐射半径" prop="positionRadius" class="no-first-el-form-item">
                  <el-input v-model="searchForm.positionRadius" step-strictly :step="1"
                            controls-position="right"
                  >
                    <template slot="append">米</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="title_card">位置</div>
            </div>
            <div style="position: relative">
              <div v-loading="typeLoading" class="search_card">
                <!--                <el-form-item label="类型" style="margin-bottom: 12px;margin-left: 20px">-->
                <!--                  <el-switch @change="typeChange" :disabled="typeSwitchDisabled" v-model="searchForm.type"-->
                <!--                             active-text="点位类型" inactive-text="套餐类型"-->
                <!--                             :active-value="1" :inactive-value="0"-->
                <!--                  ></el-switch>-->
                <!--                </el-form-item>-->
                <el-form-item v-for="item in pointTypeProject"
                              v-if="(item.id === 84 && hasLargeScreenType)||item.id !== 84"
                              :key="item.id" :label="getProjectName(item.id)" prop="buildingList"
                              style="margin-bottom: 12px" class="no-first-el-form-item"
                >
                  <el-select :ref="'project'+item.id" v-model="selectBuildingMap[item.id]" clearable multiple
                             placeholder="请选择"
                             value-key="id"
                             style="width: 300px" filterable
                             @change="(val)=>{projectChange(val,item.id)}"
                  >
                    <el-option
                      v-for="building in buildingMap[item.id]"
                      :key="building.id"
                      :label="building.name"
                      :value="building"
                    >
                    </el-option>
                  </el-select>
                  <div v-show="(selectBuildingMap[item.id]||[]).length>0" style="width: 300px;color: #aaa;">
                    已选中<span style="color: #0081ff;">{{ (selectBuildingMap[item.id] || []).length }}</span>个楼盘
                  </div>
                </el-form-item>
                <el-form-item v-for="item in comboTypeProject"
                              :label="getProjectName(item.id)" :key="item.id"
                              style="margin-bottom: 12px" class="no-first-el-form-item"
                              @change="(val)=>{projectChange(val,item.id)}"
                >
                  <el-select :ref="'project'+item.id" v-model="selectBuildingMap[item.id]" clearable multiple
                             placeholder="请选择" value-key="id"
                             style="width: 300px" filterable
                  >
                    <el-option
                      v-for="building in buildingMap[item.id]"
                      :key="building.id"
                      :label="building.name"
                      :value="building"
                    />
                  </el-select>
                  <div v-show="(selectBuildingMap[item.id]||[]).length>0" style="width: 300px;color: #aaa;">
                    已选中<span style="color: #0081ff;">{{ (selectBuildingMap[item.id] || []).length }}</span>个楼盘
                  </div>
                </el-form-item>
                <el-form-item label="楼盘辐射" prop="buildingRadiation" style="margin-bottom: 12px"
                              class="no-first-el-form-item"
                >
                  <el-switch v-model="searchForm.buildingRadiation" active-text="是" inactive-text="否"/>
                </el-form-item>
                <el-form-item v-show="searchForm.buildingRadiation" style="margin-bottom: 12px" label="辐射半径"
                              prop="buildingRadius"
                              class="no-first-el-form-item"
                >
                  <el-input v-model="searchForm.buildingRadius" step-strictly :step="1"
                            controls-position="right"
                  >
                    <template slot="append">米</template>
                  </el-input>
                </el-form-item>
                <el-form-item style="margin-bottom: 12px" class="no-first-el-form-item">
                  <el-tooltip slot="label" placement="top" content="使用模板导入，快速选中楼盘">
                    <span>导入楼盘<i class="el-icon-question"></i></span>
                  </el-tooltip>
                  <el-button style="text-decoration: underline;float: left" size="mini" type="text"
                             @click="downloadExcel"
                  >下载模板
                  </el-button>
                  <el-upload style="float:left;margin-left: 10px" :action="upFileUrl" :headers="uploadHeaders"
                             :on-success="success" :show-file-list="false" :before-upload="beforeAvatarUpload"
                             :on-error="error"
                  >
                    <el-button style="text-decoration: underline" size="mini" type="text">批量导入</el-button>
                  </el-upload>
                </el-form-item>
              </div>
              <div class="title_card">项目</div>
            </div>
            <div style="position: relative">
              <div class="search_card">
                <el-form-item label="禁投行业" prop="prohibitIndustryId" style="margin-left: 20px">
                  <el-select v-model="searchForm.prohibitIndustryId" clearable placeholder="请选择" style="width: 300px">
                    <el-option
                      v-for="item in no_voting_industry_arr"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </div>
              <div class="title_card">其他</div>
            </div>
            <div v-if="searchForm.type==1" style="position: relative">
              <div class="search_card">
                <el-form-item label="点位类型" prop="pointTypeIdList" style="margin-left: 20px">
                  <el-select ref="point" v-model="searchForm.pointTypeIdList" clearable multiple placeholder="请选择"
                             style="width: 300px" @change="pointTypeChange"
                  >
                    <el-option
                      v-for="item in point_type_arr"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="containBuildingId" prop="floorList" class="no-first-el-form-item">
                  <el-tooltip slot="label" placement="top" content="针对电梯智能框">
                    <span>限制楼层<i class="el-icon-question"></i></span>
                  </el-tooltip>
                  <el-select ref="floor" v-model="searchForm.floorList" multiple clearable placeholder="请选择">
                    <el-option
                      v-for="item in floorList"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="containComprehensiveMarketId" prop="abType"
                              class="no-first-el-form-item"
                >
                  <el-tooltip slot="label" placement="top" content="针对综合市场">
                    <span>限制AB面<i class="el-icon-question"></i></span>
                  </el-tooltip>
                  <el-radio-group v-model="searchForm.abType">
                    <el-radio-button label="A">A面</el-radio-button>
                    <el-radio-button label="B">B面</el-radio-button>
                    <el-tooltip effect="dark" content="AB面捆绑 必须同时选中" placement="top">
                      <el-radio-button label="AB">AB捆绑<i class="el-icon-question"></i></el-radio-button>
                    </el-tooltip>
                  </el-radio-group>
                </el-form-item>
              </div>
              <div class="title_card">{{ searchForm.type ? '点位' : '套餐' }}</div>
            </div>
          </el-form>
        </div>
      </transition>
      <div class="button_box">
        <el-button v-show="show" size="mini" type="primary" plain @click="search">搜索</el-button>
        <el-button v-show="show" size="mini" type="info" plain @click="resetForm('searchForm')">重置</el-button>
        <el-button size="mini" plain :icon="show?'el-icon-caret-top':'el-icon-caret-bottom'" circle
                   @click="resetInputHeight"
        />
      </div>
    </div>
    <div
      v-show="selectPointArr.find(item=>item.id == 1) == undefined||selectPointArr.find(item=>item.id == 9) == undefined||buildingTableData.length>0"
      style="height: 20px"
    />
    <div
      v-if="(selectPointArr.find(item=>item.id == 1) != undefined||selectPointArr.find(item=>item.id == 9) != undefined)&&buildingTableData.length>0&&isCombo==1"
      class="rule_box"
    >
      <el-divider content-position="left">规则过滤</el-divider>
      <div class="rule_filter_card_box flex flex-wrap justify-start align-center">
        <el-card v-if="selectPointArr.find(item=>item.id == 1) != undefined" class="box-card" shadow="never">
          <div slot="header" class="text-bold">
            <span>电梯智能框</span>
          </div>
          <div class="flex flex-no-wrap justify-start align-center card_body">
            <el-card class="box-card" shadow="never">
              <el-switch v-model="rule_filter.open_residential_quarters" class="margin-right-xs"
                         @change="openUtil"
              />
              一单元
              <el-input-number v-model="rule_filter.residential_quarters_num" :controls="false" :min="1" size="mini"
                               step-strictly class="margin-right-xs" @change="(val)=>{utilInputChange(val)}"
              />
              个
            </el-card>
            <el-card class="box-card" shadow="never">
              <el-switch v-model="rule_filter.open_floor" class="margin-right-xs" @change="openFloor"/>
              一层1个
            </el-card>
          </div>
        </el-card>
        <el-card v-if="selectPointArr.find(item=>item.id == 9) != undefined" class="box-card" shadow="never">
          <div slot="header" class="text-bold">
            <span>综合市场</span>
          </div>
          <div class="flex flex-no-wrap justify-start align-center card_body">
            <el-card class="box-card" shadow="never">
              <el-switch v-model="rule_filter.open_market" class="margin-right-xs" @change="openMarket"/>
              一市场
              <el-input-number v-model="rule_filter.market_num" :controls="false"
                               size="mini" :min="searchForm.abType == 'AB'?2:1" step-strictly
                               :step="searchForm.abType == 'AB'?2:1"
                               class="margin-right-xs"
                               @change="(val)=>{marketInputChange(val)}"
              />
              个
            </el-card>
          </div>
        </el-card>
      </div>
    </div>
    <div
      v-if="(selectPointArr.find(item=>item.id == 1) != undefined||selectPointArr.find(item=>item.id == 9) != undefined)&&buildingTableData.length>0&&isCombo==1"
      class="rule_box"
    >
      <el-divider content-position="left">快速选中</el-divider>
      <el-form :model="quickSelection" :inline="true" size="mini" class="quickSelectionForm">
        <div class="flex flex-wrap justify-start align-center">
          <el-card v-if="selectPointArr.find(item=>item.id == 1) != undefined" class="box-card" shadow="never">
            <span slot="header" class="text-bold">电梯智能框</span>
            <el-form-item class="flex flex-no-wrap justify-start align-center card_body" label="楼层" prop="floorList">
              <el-checkbox-group v-model="quickSelection.floorList" @change="(val)=>{floorQuickSelection(val,true)}">
                <el-checkbox v-for="item in floorList" :key="item" :label="item">{{ item }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-card>
          <el-card v-if="selectPointArr.find(item=>item.id == 9) != undefined" class="box-card" shadow="never">
            <span slot="header" class="text-bold">综合市场</span>
            <el-form-item class="flex flex-no-wrap justify-start align-center card_body" label="AB面" prop="surfaceList">
              <el-checkbox-group v-model="quickSelection.surfaceList"
                                 @change="(val)=>{surfaceQuickSelection(val,true)}"
              >
                <el-checkbox :label="57">A面</el-checkbox>
                <el-checkbox :label="58">B面</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-card>
        </div>
      </el-form>
    </div>
    <div v-if="selectPointArr.length>0 && isCombo==1" class="assign_points_box">
      <el-divider content-position="left">点位分配</el-divider>
      <div v-for="item in selectPointArr" :key="item.id"
           style="font-size: 13px;font-weight: 600;color: #606266;margin-top: 10px"
      >
        分配总数（{{ item.name }}<span style="color: #0081ff;padding-left: 10px">总：{{ item.count }}个</span>)
        <el-input-number v-model="item.num" style="width: 120px;margin-left: 10px" size="mini" step-strictly
                         :controls="false"
                         :min="0"
                         @change="(value)=>{pointAllocationInputChange(value,item.id,item)}"
        />
        <span style="margin-left: 5px">个</span>
        <span v-if="item.unassignedNum!=0" style="margin-left: 20px">未分配数</span>
        <span v-if="item.unassignedNum!=0" style="margin-left: 20px;color: #e54d42;">{{ item.unassignedNum }}个</span>
      </div>
    </div>
    <div v-if="isCombo == 0">
      <el-divider content-position="left">套餐分配</el-divider>
      <div v-for="item in comboSum" :key="item.id"
           style="font-size: 13px;font-weight: 600;color: #606266;margin-top: 10px"
      >
        分配总数:{{ item.name }}
        <el-input-number v-model="item.distributeNum" style="width: 120px;margin-left: 10px" size="mini" step-strictly
                         :controls="false" :step="1"
                         :min="0" @change="(val,oldVal)=>{autoDistributionCombo(item.id,val,oldVal)}"
        />
        <span style="margin-left: 5px">个</span>
        <span v-if="item.noDistributeNum!=0" style="margin-left: 20px">未分配数</span>
        <span v-if="item.noDistributeNum!=0" style="margin-left: 20px;color: #e54d42;">{{
            item.noDistributeNum
          }}个</span>
      </div>
    </div>
    <el-table v-if="firstSearch" :data="buildingTableData" border
              style="width: 100%;margin-top: 80px"
              stripe max-height="700px"
              header-row-class-name="text-bold table-herder" size="mini" :show-summary="true"
              :summary-method="pointSum"
    >
      <el-table-column label="序号" width="50" align="center">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="name" label="楼盘" min-width="100" header-align="center"/>
      <el-table-column prop="address" label="地址" min-width="150" header-align="center"/>
      <el-table-column v-if="isCombo == 1" v-for="point in selectPointArr" :key="point.id" align="center"
                       :label="getPointTypeName(point.id)"
      >
        <template slot-scope="scope">
          <div>
            <el-input-number v-if="scope.row.pointTypeCountVOMap[point.id].allCanSelectNum>0"
                             v-model="scope.row.pointTypeCountVOMap[point.id].to" size="mini"
                             step-strictly style="width:50%" :controls="false"
                             :max="scope.row.pointTypeCountVOMap[point.id].allCanSelectNum"
                             :min="0"
                             @change="(value,oldValue)=>{tableInputChange(scope.row,value-oldValue,point.id)}"
            />
            <span v-if="scope.row.pointTypeCountVOMap[point.id].allCanSelectNum>0" style="margin-left: 10px">/</span>
            <el-button size="mini" type="text"
                       :class="scope.row.pointTypeCountVOMap[point.id].allCanSelectNum<=0?'text-underline text-bold':'text-underline text-bold text-green'"
                       :disabled="scope.row.pointTypeCountVOMap[point.id].allCanSelectNum<=0"
                       @click="showPointDetail(scope.row.pointTypeCountVOMap[point.id],scope.row.id,point.id)"
            >
              {{ scope.row.pointTypeCountVOMap[point.id].allCanSelectNum }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      <!--套餐信息-->
      <el-table-column v-if="isCombo == 0" width="300" label="套餐" header-align="center">
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.comboCountInfoList" :key="index"
               style="border: 1px solid #eee;margin: 15px 5px;padding: 10px 5px;position: relative"
          >
            <div
              style="font-size: 14px;font-weight: bold;position: absolute;top: -10px;background-color: white;width: 40px;left: 10px;"
            >{{ item.name }}
            </div>
            <div v-for="(tmp,i) in item.ruleList" :key="i" style="margin: 2px 0;font-size: 14px">
              <span>{{ tmp.name }}：</span>
              <span :class=" tmp.count>0?'text-red text-bold':''">{{ tmp.count }}</span>个
            </div>
          </div>
          <div style="text-align: center">
            <el-button type="primary" size="mini" @click="showBuildingCombo(scope.row)">修改</el-button>
          </div>
        </template>
      </el-table-column>
      <!--点位数据-->
      <el-table-column v-if="isCombo == 0" align="center"
                       v-for="point in comboPointTypeArr" :key="point.id"
                       :label="getPointTypeName(point.id)"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.pointTypeCountVOMap[point.id].point_type_count>0">
            {{ scope.row.pointTypeCountVOMap[point.id].to }}
          </span>
          <span v-if="scope.row.pointTypeCountVOMap[point.id].point_type_count>0">/</span>
          <el-button size="mini" type="text"
                     :class="scope.row.pointTypeCountVOMap[point.id].point_type_count == 0?'text-underline text-bold':'text-underline text-bold text-green'"
                     :disabled="scope.row.pointTypeCountVOMap[point.id].point_type_count == 0"
                     @click="showPointDetail(scope.row.pointTypeCountVOMap[point.id],scope.row.id,point.id,scope.row.pointTypeCountVOMap[point.id].to)"
          >
            {{ scope.row.pointTypeCountVOMap[point.id].point_type_count }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="50px" align="center">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeTable(scope.$index)"/>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="firstSearch" style="padding-bottom: 20px;text-align: center;margin-top: 20px">
      <el-button size="mini" @click="beforeClose">取消</el-button>
      <el-button type="primary" size="mini" @click="addConfig">确定</el-button>
    </div>
    <el-dialog title="精准选点" :visible.sync="pointSelectionDialogVisible" width="1200px" append-to-body center
               @close="closePointSelectionDialog"
    >
      <div style="font-size: 16px">
        共计<span class="text-green">{{ pointDialogData.point_type_count }}</span>个空闲点位，
        最多可选<span class="text-red">{{ pointDialogData.point_count }}</span>，
        已选择<span class="text-blue">{{ pointDialogData.point_checked_count }}</span>个
        <span v-if="isCombo==0">必须选择<span class="text-red">{{ pointDialogData.need_select_count }}</span>个</span>
        <el-checkbox v-model="pointDialogData.isAllSelect"
                     label="全选"
                     @change="(val)=>{allSelectCheckBox(val,pointDialogData.mediaPointData,pointDialogData.point_count-pointDialogData.point_checked_count,pointDialogData.point_type_id)}"
        />
        <div v-if="pointDialogData.point_type_id==1" class="quick_selection_box">
          <div class="flex flex-no-wrap justify-start align-center">
            <span style="margin-right: 10px">楼层：</span>
            <el-checkbox-group v-model="dialogQuickSelection.floorList"
                               @change="(val)=>{floorQuickSelection(val)}"
            >
              <el-checkbox v-for="item in floorList" :key="item" :label="item">{{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div v-if="pointDialogData.point_type_id==9" class="quick_selection_box">
          <div class="flex flex-no-wrap justify-start align-center">
            <span style="margin-right: 10px">AB面：</span>
            <el-checkbox-group v-model="dialogQuickSelection.surfaceList"
                               @change="(val)=>{surfaceQuickSelection(val)}"
            >
              <el-checkbox :label="57">A面</el-checkbox>
              <el-checkbox :label="58">B面</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <el-divider class="split-line"/>
      <div v-if="pointSelectionDialogVisible" style="max-height: 500px;overflow-y: auto">
        <div v-if="pointDialogData.point_type_id == 1">
          <el-row v-if="rule_filter.open_residential_quarters&&rule_filter.open_floor" type="flex"
                  style="flex-wrap: wrap"
          >
            <div v-for="(item,key) in pointDialogData.mediaPointData" class="flex flex-no-wrap align-start"
                 style="padding: 10px;margin: 5px;border: 1px solid #ddd;border-radius: 5px;"
            >
              <div class="title flex flex-no-wrap align-start"
                   style="padding: 5px 5px 10px;border-bottom: 1px solid #ddd;"
              >
                <div class="unit text-blue text-bold text-xxl">{{ key ? key : '未标明楼号和单元' }}</div>
              </div>
              <div v-for="(val,k) in item"
                   style="padding: 10px;margin: 5px;border: 1px solid #ddd;border-radius: 5px;"
              >
                <div class="flex flex-no-wrap"
                     style="padding: 5px 5px 10px;border-bottom: 1px solid #ddd;justify-content: space-between;"
                >
                  <div class="unit text-green text-bold text-xxl">{{ k ? k : '未标明层' }}</div>
                  <div class="tip" style="margin-left: 15px;height:20px;line-height: 20px">最多选择<span class="text-red"
                  >1</span>个设备
                  </div>
                </div>
                <div class="flex flex-wrap align-start">
                  <div v-for="tmp in val" :class="tmp.checked?'checked-box item':'item'"
                       @click="itemChange(pointDialogData.point_type_id,tmp,val,item)"
                  >
                    <div style="display: table-cell;vertical-align: middle;">
                      {{ tmp.code }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-row>
          <!--开启单元或楼层过滤-->
          <el-row
            v-if="(rule_filter.open_residential_quarters||rule_filter.open_floor)&&!(rule_filter.open_residential_quarters&&rule_filter.open_floor)"
            type="flex" style="flex-wrap: wrap"
          >
            <div v-for="(item,key) in pointDialogData.mediaPointData" class="flex flex-no-wrap align-start"
                 style="padding: 10px;margin: 5px;border: 1px solid #ddd;border-radius: 5px;"
            >
              <div class="title flex flex-no-wrap align-start"
                   style="padding: 5px 5px 10px;border-bottom: 1px solid #ddd;"
              >
                <div class="unit text-blue text-bold text-xxl">{{ key ? key : '未标明楼号和单元' }}</div>
                <div style="margin-left: 15px;height:20px;line-height: 20px">最多选择<span class="text-red"
                >{{ rule_filter.open_floor ? '1' : rule_filter.residential_quarters_num }}</span>个设备
                </div>
              </div>
              <div v-for="tmp in item" :class="tmp.checked?'checked-box item':'item'"
                   @click="itemChange(pointDialogData.point_type_id,tmp,item)"
              >
                <div style="display: table-cell;vertical-align: middle;">
                  {{ tmp.code }}
                </div>
              </div>
            </div>
          </el-row>
          <el-row v-if="!rule_filter.open_residential_quarters && !rule_filter.open_floor" type="flex"
                  style="flex-wrap: wrap"
          >
            <div v-for="item in pointDialogData.mediaPointData" :class="item.checked?'checked-box item':'item'"
                 @click="itemChange(pointDialogData.point_type_id,item,pointDialogData.mediaPointData)"
            >
              <div style="display: table-cell;vertical-align: middle;">
                {{
                  (item.building_number != null ? item.building_number + '号楼' : '') +
                  (item.unit_number != null ? item.unit_number + '单元' : '') +
                  (item.floor != null ? item.floor + '层' : '') + item.code
                }}
              </div>
            </div>
          </el-row>
        </div>
        <!--开启市场过滤-->
        <div v-if="pointDialogData.point_type_id == 9">
          <el-row type="flex" style="flex-wrap: wrap">
            <div v-for="item in pointDialogData.mediaPointData" :class="item.checked?'checked-box item':'item'"
                 @click="itemChange(pointDialogData.point_type_id,item,pointDialogData.mediaPointData)"
            >
              <div style="display: table-cell;vertical-align: middle;">
                {{
                  (item.building_number != null ? item.building_number + '号楼' : '') +
                  (item.unit_number != null ? item.unit_number + '单元' : '') +
                  (item.floor != null ? item.floor + '层' : '') + item.code
                }}
              </div>
            </div>
          </el-row>
        </div>
        <!--既不是电梯智能框又不是综合市场-->
        <el-row v-if="pointDialogData.point_type_id != 1&&pointDialogData.point_type_id != 9" type="flex"
                style="flex-wrap: wrap"
        >
          <div v-for="item in pointDialogData.mediaPointData" :class="item.checked?'checked-box item':'item'"
               @click="itemChange(pointDialogData.point_type_id,item,pointDialogData.mediaPointData,null,false,pointDialogData.point_count,pointDialogData.point_checked_count)"
          >
            <div style="display: table-cell;vertical-align: middle;">
              {{
                (item.building_number != null ? item.building_number + '号楼' : '') +
                (item.unit_number != null ? item.unit_number + '单元' : '') +
                (item.floor != null ? item.floor + '层' : '') + item.code
              }}
            </div>
          </div>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pointSelectionDialogVisible =false">取消</el-button>
        <el-button type="primary" @click="pointDialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="地址搜索" :visible.sync="addressDialogVisible" width="1200px" center append-to-body
               @close="closeAddressDialog"
    >
      <el-row>
        <el-col :span="12" style="padding: 0 10px">
          <el-divider>相似地址</el-divider>
          <el-table v-loading="addressTableLoading" :data="addressTableData" border row-key="id">
            <el-table-column type="index" label="序号" width="50" align="center">
              <template slot-scope="scope">
                <span>{{ (addressListParams.page - 1) * addressListParams.page_size + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="地址" align="center" min-width="350" show-overflow-tooltip>
              <template slot-scope="scope">
                <span class="address_title">{{ scope.row.title }}&nbsp;&nbsp;&nbsp;</span>
                <span style="color: #aaa">{{ scope.row.address }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <el-button type="primary" size="small"
                           :disabled="chooseAddressTableData.find(item=>item.id==scope.row.id)!=undefined"
                           @click="selectAddress(scope.row)"
                >选中
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="addressListParams.page"
            :page-size="addressListParams.page_size"
            layout="total,prev, pager, next, jumper"
            :total="addressTotal"
            @current-change="handleCurrentChange"
          />
        </el-col>
        <el-col :span="12" style="padding: 0 10px;overflow: auto">
          <el-divider>选中地址</el-divider>
          <el-table :data="chooseAddressTableData" border max-height="618" tooltip-effect="dark"
                    style="width: 100%;" highlight-current-row row-key="id"
          >
            <el-table-column type="index" label="序号" width="50" align="center">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="地址" align="center" width="404" show-overflow-tooltip>
              <template slot-scope="scope">
                <span class="address_title">{{ scope.row.title }}&nbsp;&nbsp;&nbsp;</span>
                <span style="color: #aaa">{{ scope.row.address }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100px">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="removeAddress(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="determine">确 定</el-button>
      </span>
    </el-dialog>
    <combo-distribute-dialog :combo-data-list="combo_data_list" :building-name="comboDialogTmpBuildingName"
                             :show-dialog="comboDistributeDialogShow" :combo-point-type-arr="comboPointTypeArr"
                             @shut="closeComboDialog" @save="editBuildingCombo"
    ></combo-distribute-dialog>
    <!--精准选点组件-->
    <precise-point-selection :show="precisePointSelectionDialogVisible" :point-data="tmpPointDataList"
                             :media-type-id="clickMediaTypeId" :all-can-select-count="allCanSelectNum"
                             :rule-arr="ruleArr" :need-select-count="need_select_count" :is-combo="isCombo == 0"
                             @close="closePrecisePointSelectionDialog" @save="saveSelectPoint"
    ></precise-point-selection>
  </el-dialog>
</template>

<script>
import { combo_info, search, searchAll } from '@/api/business/intention_scheme'
import { list_all3rd_bycode } from '@/api/business/setting/dict'
import {
  area_list,
  get_media_types,
  getBuildingImportExcel,
  list_all,
  list_floor_selections,
  list_media_types,
  search_address_by_page
} from '@/api/building/building'
import comboDistributeDialog from '@/components/PointPlanSetting/comboDistributeDialog'
import precisePointSelection from '@/components/PointPlanSetting/precisePointSelection'
import { getToken } from '@/utils/auth'
import { getUploadExcelUrl } from '@/api/upload'
import { formatDate } from '@/utils/util'

export default {
  name: 'PositionSelection', // 选位筛选弹框
  components: {
    comboDistributeDialog,
    precisePointSelection
  },
  props: {
    // 弹框是否显示
    dialogShow: {
      type: Boolean,
      default: false
    },
    // 时间段
    dateRange: {
      type: Array,
      default() {
        return [formatDate(new Date()), formatDate(new Date())]
      }
    },
    // 点位数组
    pointTypeIdList: {
      type: Array,
      default() {
        return []
      }
    },
    // 排除的楼盘数据
    excludeBuildingIdList: {
      type: Array,
      default() {
        return []
      }
    },
    // 排除的点位数据
    excludeMediaIdList: {
      type: Array,
      default() {
        return []
      }
    },
    // 楼盘数据
    buildingList: {
      type: Array,
      default() {
        return []
      }
    },
    // 是否禁用类型选择
    typeSwitchDisabled: {
      type: Boolean,
      default: true
    },
    // 选择器类型
    configType: {
      type: Number,
      default: 1
    },
    excludeSaleChooseId: {
      type: Number,
      default: null
    },
    // 组件类型 1：为原始组件 2：为市场单使用的组件
    componentType: {
      type: Number,
      default: 1
    },
    // save方法回调的数据结构 1：市场单使用的数据结构 2：原始组件使用的数据结构
    responseType: {
      type: Number,
      default: 1
    },
    hasLargeScreenType: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: true,
      searchForm: {
        beginDate: null,
        endDate: null,
        pcaList: [], // 行政规划
        address: null, // 地址
        positionRadius: 1000,
        buildingList: [], // 选中的楼盘信息
        buildingRadiation: false, // 楼盘是否辐射
        buildingRadius: 1000, // 楼盘辐射距离
        prohibitIndustryId: null, // 禁投行业
        pointTypeIdList: [],
        floorList: [],
        abType: 'ALL',
        type: 1, // 0 套餐 1 点位
        exclude_media_id_list: [],
        exclude_building_id_list: [],
        positionLocationList: []
      },
      rules: {
        pointTypeIdList: [
          { type: 'array', required: true, message: '请至少选择一个点位类型', trigger: 'change' }
        ]
      },
      adcodes: [],
      point_type_arr: [],
      no_voting_industry_arr: [],
      floorList: [],
      addressListParams: {
        page: 1,
        page_size: 10,
        boundary: '320400'
      },
      addressTotal: null,
      addressDialogVisible: false,
      addressTableData: [],
      addressTableLoading: false,
      chooseAddressTableData: [],
      addressDataList: [],
      buildingArr: [],
      // 规则过滤
      rule_filter: {
        open_residential_quarters: false, // 是否开启小区过滤
        residential_quarters_num: 1, // 小区过滤数
        open_floor: false, // 是否开启楼层过滤
        open_market: false, // 是否开启综合市场过滤
        market_num: 1 // 市场过滤数字
      },
      tmpSelectPointArr: [],
      // 选择的点位信息
      selectPointArr: [],
      buildingTableData: [], // 楼盘数据
      pointSelectionDialogVisible: false, // 选点弹窗
      pointDialogData: {
        isAllSelect: false,
        id: null,
        need_select_count: null,
        point_type_id: null, // 点位类型
        point_count: null, // 可选总数
        point_type_count: null, // 总数
        point_checked_count: null, // 已选择数量
        mediaPointData: null, // 点位数据
        mediaPointList: [],
        selectAllArr: []
      },
      firstSearch: false,
      allPointTypeArr: [],
      comboInfoList: [], // 组合详情
      comboSum: [], // 套餐数量
      isCombo: 2, // 2都不显示 1 显示普通点位的点位分配和过滤 0显示套餐类型的套餐分配
      combo_data_list: [], // 套餐信息数据
      comboDistributeDialogShow: false,
      comboDialogTmpBuildingId: null,
      comboDialogTmpBuildingName: '',
      projectTypeArr: [],
      buildingMap: {},
      selectBuildingMap: {},
      typeLoading: false,
      quickSelection: {
        floorList: [],
        surfaceList: []
      },
      dialogQuickSelection: {
        floorList: [],
        surfaceList: []
      },
      precisePointSelectionDialogVisible: false,
      clickMediaTypeId: 0,
      tmpPointDataList: [],
      ruleArr: [],
      allCanSelectNum: 0,
      need_select_count: 0,
      uploadHeaders: {},
      upFileUrl: '',
      loading: null
    }
  },
  computed: {
    // 点位选择框是否包含电梯智能框类型
    containBuildingId() {
      return this.searchForm.pointTypeIdList.find(item => item == 1) != undefined
    },
    // 点位选择框是否包含综合市场类型
    containComprehensiveMarketId() {
      return this.searchForm.pointTypeIdList.find(item => item == 9) != undefined
    },
    comboPointTypeArr() {
      return this.allPointTypeArr.filter(item => item.gas)
    },
    pointTypeProject() {
      return this.projectTypeArr.filter(item => item.id != 81)
    },
    comboTypeProject() {
      return this.projectTypeArr.filter(item => item.id == 81)
    }
  },
  async created() {
    if (getToken()) {
      this.uploadHeaders['Authorization'] = getToken()
    }
    this.upFileUrl = getUploadExcelUrl()
    this.searchForm.pointTypeIdList = this.pointTypeIdList
    this.searchForm.buildingList = this.buildingList
    this.searchForm.exclude_building_id_list = this.excludeBuildingIdList
    this.searchForm.exclude_media_id_list = this.excludeMediaIdList
    this.initFloorList() // 初始化楼层数据
    this.initPointType() // 初始化点位类型数据
    this.initNoVotingIndustry() // 初始化禁投行业数据
    await this.initProjectTypeArr() // 初始化项目类型数据
    this.initBuildingArr() // 初始化楼盘数据
    this.initAdCode() // 初始化行政规划
    this.initComboType() // 初始化套餐点位类型
    // this.initComboDetail() // 初始化套餐类型数据

  },
  methods: {
    resetInputHeight() {
      this.show = !this.show
      if (this.show) {
        setTimeout(() => {
          this.projectTypeArr.forEach(item => {
            if (this.$refs['project' + item.id]) {
              this.$refs['project' + item.id][0].resetInputHeight()
            }
          })
          if (this.$refs['floor']) {
            this.$refs['floor'].resetInputHeight()
          }
          this.$refs['adcode'].resetInputHeight()
          this.$refs['point'].resetInputHeight()
        }, 200)
      }
    },
    search() {
      if (this.searchForm.pointTypeIdList == null || this.searchForm.pointTypeIdList.length == undefined || this.searchForm.pointTypeIdList.length == 0) {
        this.$message.error('请至少选择一种点位类型')
      } else {
        this.show = !this.show
        this.firstSearch = true
        this.rule_filter = {
          open_residential_quarters: false, // 是否开启小区过滤
          residential_quarters_num: 1, // 小区过滤数
          open_floor: false, // 是否开启楼层过滤
          open_market: false, // 是否开启综合市场过滤
          market_num: 1 // 市场过滤数字
        }
        this.quickSelection = {
          floorList: [],
          surfaceList: []
        }
        this.searchForm.buildingList = []
        for (const key in this.selectBuildingMap) {
          this.selectBuildingMap[key].forEach(item => {
            this.searchForm.buildingList.push(Object.assign({}, item))
          })
        }
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const req = Object.assign({ exclude_sale_choose_id: this.excludeSaleChooseId }, this.searchForm)
        if (this.componentType === 2) {
          if (!this.hasLargeScreenType) {
            req.pointTypeIdList = req.pointTypeIdList.filter(id => id !== 11)
          }
          searchAll(req).then(
            res => {
              this.isCombo = this.searchForm.type
              this.selectPointArr = []
              for (let i = 0; i < this.tmpSelectPointArr.length; i++) {
                var tmp = this.tmpSelectPointArr[i]
                this.selectPointArr.push(Object.assign({}, tmp))
              }
              this.buildingTableData = res.data
              // 遍历数据增加属性 当为普通选点时
              if (this.searchForm.type == 1) {
                for (let i = 0; i < this.buildingTableData.length; i++) {
                  var tmp = this.buildingTableData[i].pointTypeCountVOMap
                  for (const tmpKey in tmp) {
                    this.$set(tmp[tmpKey], 'to', 0)// 添加已选择数
                    this.$set(tmp[tmpKey], 'canSelectNum', 0)// 添加能选择数
                    this.$set(tmp[tmpKey], 'allCanSelectNum', tmp[tmpKey].point_type_count) // 添加总选择数
                    for (let j = 0; j < tmp[tmpKey].mediaPointList.length; j++) {
                      this.$set(tmp[tmpKey].mediaPointList[j], 'checked', false)
                    }
                  }
                }
                this.formatPointDistribution()
              } else {
                this.comboSum = []
                this.selectPointArr = []
                for (let i = 0; i < this.comboInfoList.length; i++) {
                  let tmp = this.comboInfoList[i]
                  this.comboSum.push(
                    {
                      id: tmp.combo_id,
                      name: String.fromCharCode(65 + i) + '套餐',
                      distributeNum: 0,
                      noDistributeNum: 0
                    }
                  )
                }
                // 楼盘数据格式化
                for (let i = 0; i < this.buildingTableData.length; i++) {
                  this.buildingTableData[i].comboCountInfoList = []
                  var tmp = this.buildingTableData[i].pointTypeCountVOMap
                  for (const tmpKey in tmp) {
                    this.$set(tmp[tmpKey], 'to', 0)// 添加已选择数
                    for (let j = 0; j < tmp[tmpKey].mediaPointList.length; j++) {
                      this.$set(tmp[tmpKey].mediaPointList[j], 'checked', false)
                    }
                  }
                  // 增加comboCountInfoList
                  for (let j = 0; j < this.comboInfoList.length; j++) {
                    let temp = this.comboInfoList[j]
                    let t = {
                      id: temp.combo_id,
                      count: 0,
                      name: String.fromCharCode(j + 65) + '套餐',
                      ruleList: []
                    }
                    for (let k = 0; k < temp.ruleList.length; k++) {
                      let item = temp.ruleList[k]
                      let tmp = {
                        building_area_id: this.buildingTableData[i].id,
                        combo_id: temp.combo_id,
                        rule_id: item.rule_id,
                        count: 0,
                        name: String.fromCharCode(k + 65) + '组合(' + item.rule_name + ')'
                      }
                      t.ruleList.push(tmp)
                    }
                    this.buildingTableData[i].comboCountInfoList.push(t)
                  }
                }
              }
              loading.close()
            }
          ).catch(() => {
            loading.close()
          })
        } else {
          search(req).then(
            res => {
              this.isCombo = this.searchForm.type
              this.selectPointArr = []
              for (let i = 0; i < this.tmpSelectPointArr.length; i++) {
                var tmp = this.tmpSelectPointArr[i]
                this.selectPointArr.push(Object.assign({}, tmp))
              }
              this.buildingTableData = res.data
              // 遍历数据增加属性 当为普通选点时
              if (this.searchForm.type == 1) {
                for (let i = 0; i < this.buildingTableData.length; i++) {
                  var tmp = this.buildingTableData[i].pointTypeCountVOMap
                  for (const tmpKey in tmp) {
                    this.$set(tmp[tmpKey], 'to', 0)// 添加已选择数
                    this.$set(tmp[tmpKey], 'canSelectNum', 0)// 添加能选择数
                    this.$set(tmp[tmpKey], 'allCanSelectNum', tmp[tmpKey].point_type_count) // 添加总选择数
                    for (let j = 0; j < tmp[tmpKey].mediaPointList.length; j++) {
                      this.$set(tmp[tmpKey].mediaPointList[j], 'checked', false)
                    }
                  }
                }
                this.formatPointDistribution()
              } else {
                this.comboSum = []
                this.selectPointArr = []
                for (let i = 0; i < this.comboInfoList.length; i++) {
                  let tmp = this.comboInfoList[i]
                  this.comboSum.push(
                    {
                      id: tmp.combo_id,
                      name: String.fromCharCode(65 + i) + '套餐',
                      distributeNum: 0,
                      noDistributeNum: 0
                    }
                  )
                }
                // 楼盘数据格式化
                for (let i = 0; i < this.buildingTableData.length; i++) {
                  this.buildingTableData[i].comboCountInfoList = []
                  var tmp = this.buildingTableData[i].pointTypeCountVOMap
                  for (const tmpKey in tmp) {
                    this.$set(tmp[tmpKey], 'to', 0)// 添加已选择数
                    for (let j = 0; j < tmp[tmpKey].mediaPointList.length; j++) {
                      this.$set(tmp[tmpKey].mediaPointList[j], 'checked', false)
                    }
                  }
                  // 增加comboCountInfoList
                  for (let j = 0; j < this.comboInfoList.length; j++) {
                    let temp = this.comboInfoList[j]
                    let t = {
                      id: temp.combo_id,
                      count: 0,
                      name: String.fromCharCode(j + 65) + '套餐',
                      ruleList: []
                    }
                    for (let k = 0; k < temp.ruleList.length; k++) {
                      let item = temp.ruleList[k]
                      let tmp = {
                        building_area_id: this.buildingTableData[i].id,
                        combo_id: temp.combo_id,
                        rule_id: item.rule_id,
                        count: 0,
                        name: String.fromCharCode(k + 65) + '组合(' + item.rule_name + ')'
                      }
                      t.ruleList.push(tmp)
                    }
                    this.buildingTableData[i].comboCountInfoList.push(t)
                  }
                }
              }
              loading.close()
            }
          ).catch(() => {
            loading.close()
          })
        }
      }
    },
    /**
     * 初始化禁投信息
     */
    initNoVotingIndustry() {
      list_all3rd_bycode({ code: 'khxg-hy' }).then(
        res => {
          this.no_voting_industry_arr = res.data
        }
      )
    },
    /**
     * 初始化项目类型数组
     */
    initProjectTypeArr() {
      this.typeLoading = true
      list_all3rd_bycode({ code: 'xmxg-fl' }).then(
        res => {
          this.projectTypeArr = res.data.map(item => {
            return {
              id: item.id,
              name: item.name
            }
          })
          this.pointTypeProject.forEach(item => {
            if (!this.selectBuildingMap.hasOwnProperty(item.id)) {
              this.$set(this.selectBuildingMap, item.id, [])
            }
          })
        }
      )
    },
    // 获取项目类型名称
    getProjectName(id) {
      return (this.projectTypeArr.find(item => item.id == id) || {}).name
    },
    /**
     * 初始化点位类型数据
     */
    initPointType() {
      get_media_types().then(
        res => {
          if (!this.hasLargeScreenType) {
            this.point_type_arr = res.data.filter(item => item.id !== 11)
          } else {
            this.point_type_arr = res.data
          }
        }
      )
    },
    /**
     * 初始化行政规划
     */
    initAdCode() {
      area_list({ pid: '320400' }).then(
        res => {
          this.adcodes = res.data
        }
      )
    },
    /**
     * 初始化加油站点位类型数据
     */
    initComboType() {
      list_media_types().then(res => {
        this.allPointTypeArr = res.data
      })
    },
    /**
     * 初始化楼盘下拉列表
     */
    initBuildingArr() {
      list_all({ ad_code: this.searchForm.pcaList }).then(res => {
        res.data.forEach(item => {
          let key = item.type_id + ''
          if (this.buildingMap.hasOwnProperty(key)) {
            this.buildingMap[key].push(
              {
                id: item.id,
                name: item.name,
                lat: item.lat,
                lng: item.lng,
                type_id: item.type_id
              }
            )
          } else {
            this.$set(this.buildingMap, parseInt(key), [{
              id: item.id,
              name: item.name,
              lat: item.lat,
              lng: item.lng,
              type_id: item.type_id
            }])
          }
        })
        this.buildingArr = res.data.map(item => {
          return {
            id: item.id,
            name: item.name,
            lat: item.lat,
            lng: item.lng,
            type_id: item.type_id
          }
        })
        this.buildingList.forEach(i => {
          let source = this.buildingArr.find(item => item.id == i)
          if (source) {
            this.selectBuildingMap[source.type_id].push(Object.assign({}, source))
          }
        })
        this.typeLoading = false
      }).catch(() => {
        this.typeLoading = false
      })
    },
    projectChange(val, id) {
      if (val.length > 0) {
        switch (id) {
          case 78: // 住宅 1
            if (this.searchForm.pointTypeIdList.find(item => item == 1) == undefined) {
              this.searchForm.pointTypeIdList.push(1)
            }
            break
          case 79: // 楼宇 2
            if (this.searchForm.pointTypeIdList.find(item => item == 2) == undefined) {
              this.searchForm.pointTypeIdList.push(2)
            }
            break
          case 80: // 路名牌 3
            if (this.searchForm.pointTypeIdList.find(item => item == 3) == undefined) {
              this.searchForm.pointTypeIdList.push(3)
            }
            break
          case 82: // 综合市场 9
            if (this.searchForm.pointTypeIdList.find(item => item == 9) == undefined) {
              this.searchForm.pointTypeIdList.push(9)
            }
            break
          case 83: // 软膜灯箱 10
            if (this.searchForm.pointTypeIdList.find(item => item == 10) == undefined) {
              this.searchForm.pointTypeIdList.push(10)
            }
            break
          case 84: // 大屏 11
            if (this.searchForm.pointTypeIdList.find(item => item == 11) == undefined) {
              this.searchForm.pointTypeIdList.push(11)
            }
            break
          case 85: // 大牌 12
            if (this.searchForm.pointTypeIdList.find(item => item == 12) == undefined) {
              this.searchForm.pointTypeIdList.push(12)
            }
            break
          case 86: // 桁架 13
            if (this.searchForm.pointTypeIdList.find(item => item == 13) == undefined) {
              this.searchForm.pointTypeIdList.push(13)
            }
            break
        }
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.searchForm.positionLocationList = []
    },
    /**
     * 获取位置信息
     */
    getLocation() {
      if (this.searchForm.address) {
        this.getAddressList()
      } else {
        this.$message.error('请输入地址')
      }
    },
    getAddressList() {
      const params = Object.assign({ keyword: this.searchForm.address }, this.addressListParams)
      this.addressTableLoading = true
      search_address_by_page(params).then(
        res => {
          this.addressTableData = res.data.data
          this.addressTableLoading = false
          this.addressTotal = res.data.count
        }
      )
      this.addressDialogVisible = true
    },
    handleCurrentChange(val) {
      this.addressListParams.page = val
      this.getAddressList()
    },
    selectAddress(row) {
      this.chooseAddressTableData.push(Object.assign({}, row))
    },
    removeAddress(index) {
      this.chooseAddressTableData.splice(index, 1)
    },
    // 点击地址搜索确认按钮
    determine() {
      const tmp = []
      for (let j = 0; j < this.chooseAddressTableData.length; j++) {
        if (this.searchForm.positionLocationList.find(item => item.id == this.chooseAddressTableData[j].id) == undefined) {
          tmp.push({
            id: this.chooseAddressTableData[j].id,
            lat: this.chooseAddressTableData[j].location.lat,
            lng: this.chooseAddressTableData[j].location.lng,
            title: this.chooseAddressTableData[j].title
          })
        }
      }
      this.searchForm.positionLocationList = this.searchForm.positionLocationList.concat(tmp)
      this.addressDialogVisible = false
    },
    closeAddressDialog() {
      this.chooseAddressTableData = []
      this.addressListParams.page = 1
      this.addressTotal = null
    },
    // 删除地址输入框下面的el-tag
    handleClose(index) {
      this.searchForm.positionLocationList.splice(index, 1)
    },
    /**
     * 点位类型选择框change事件
     * @param val
     */
    pointTypeChange(val) {
      if (val.find(item => item == 1) == undefined) {
        this.searchForm.floorList = []
      }
      if (val.find(item => item == 9) == undefined) {
        this.searchForm.abType = 'ALL'
      }
      this.tmpSelectPointArr = []
      if (val != null && val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          const tmp = this.point_type_arr.find(item => item.id == val[i])
          if (tmp) {
            this.tmpSelectPointArr.push(
              {
                id: tmp.id, // 点位类型ID
                name: tmp.name, // 点位类型名称
                count: 0, // 点位可选总数
                num: 0, // 点位分配总数
                unassignedNum: 0, // 点位未分配数
                actual_num: 0 // 实际分配数
              }
            )
          }
        }
      }
    },
    /**
     * 初始化楼层数据
     */
    initFloorList() {
      list_floor_selections().then(
        res => {
          this.floorList = res.data
        }
      )
    },
    /**
     * 删除表格楼盘
     * @param index
     */
    removeTable(index) {
      this.$confirm('确认删除该楼盘', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (let i = 0; i < this.selectPointArr.length; i++) {
          this.selectPointArr[i].count -= this.buildingTableData[index].pointTypeCountVOMap[this.selectPointArr[i].id].allCanSelectNum
        }
        this.buildingTableData.splice(index, 1)
      }).catch(() => {

      })
    },
    /**
     * 获取点位类型名称
     * @param id
     * @returns {string|*}
     */
    getPointTypeName(id) {
      const tmp = this.allPointTypeArr.find(item => item.id == id)
      if (tmp) {
        return tmp.name
      } else {
        return ''
      }
    },
    /**
     * 格式化分配数
     */
    formatPointDistribution() {
      for (let i = 0; i < this.buildingTableData.length; i++) {
        const item = this.buildingTableData[i].pointTypeCountVOMap
        for (let j = 0; j < this.selectPointArr.length; j++) {
          this.selectPointArr[j].count += item[this.selectPointArr[j].id].point_type_count
        }
      }
    },
    /**
     * 点位数量求和
     */
    pointSum(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index > 2 && index != columns.length - 1) {
          sums[index] = 0
          let s1 = 0
          let s2 = 0
          if (this.isCombo == 1) { //如果是普通点位
            for (let j = 0; j < data.length; j++) {
              s1 += data[j].pointTypeCountVOMap[this.selectPointArr[index - 3].id].to
              s2 += data[j].pointTypeCountVOMap[this.selectPointArr[index - 3].id].allCanSelectNum
            }
          } else {
            if (index == 3) {
              let map = new Map()
              for (let j = 0; j < data.length; j++) {
                data[j].comboCountInfoList.forEach(item => {
                  if (map.has(item.name)) {
                    map.set(item.name, item.count + map.get(item.name))
                  } else {
                    map.set(item.name, item.count)
                  }
                })
              }
              s1 = ''
              map.forEach(function(value, key) {
                s1 += key + '：' + value + '  '
              })
            } else {
              for (let j = 0; j < data.length; j++) {
                s1 += data[j].pointTypeCountVOMap[this.comboPointTypeArr[index - 4].id].to
                s2 += data[j].pointTypeCountVOMap[this.comboPointTypeArr[index - 4].id].point_type_count
              }
            }
          }
          if (s1 != 0 && !isNaN(s1)) {
            sums[index] = s1 + '/' + s2
          } else {
            sums[index] = s1
          }
        }
      })
      return sums
    },
    /**
     * 开启规则过滤
     */
    openRuleFilter() {
      this.selectPointArr.forEach(item => {
        item.num = 0
        item.unassignedNum = 0
        item.actual_num = 0
      }) // 清空所有分配数、未分配数、实际分配数
      this.buildingTableData.forEach(item => {
        for (const itemKey in item.pointTypeCountVOMap) {
          item.pointTypeCountVOMap[itemKey].to = 0
          item.pointTypeCountVOMap[itemKey].mediaPointList.forEach(tmp => {
            tmp.checked = false
          })
        }
      })
    },
    /**
     * 开启楼层过滤
     */
    openFloor(val) {
      this.openRuleFilter()
      this.elevatorIntelligentFrameFilter(this.rule_filter.open_residential_quarters, this.rule_filter.residential_quarters_num, val)
    },
    /**
     * 单元输入框改变事件
     */
    utilInputChange(val) {
      this.openRuleFilter()
      this.elevatorIntelligentFrameFilter(this.rule_filter.open_residential_quarters, val, this.rule_filter.open_floor)
    },
    /**
     * 开启单元过滤
     */
    openUtil(val) {
      this.openRuleFilter()
      this.elevatorIntelligentFrameFilter(val, this.rule_filter.residential_quarters_num, this.rule_filter.open_floor)
    },
    /**
     * 规则改变清空所选数和可选总数
     * @param utilOpen
     * @param utilNum
     * @param floorOpen
     */
    elevatorIntelligentFrameFilter(utilOpen, utilNum, floorOpen) {
      const typeId = 1
      let all = 0
      if (utilOpen && floorOpen) {
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const map = new Map()
          const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
          tmp.mediaPointList.forEach(item => {
            const key = (item.building_number != null ? item.building_number + '号楼' : '') + (item.unit_number != null ? item.unit_number + '单元' : '')
            const key2 = (item.floor != null ? item.floor + '层' : '')
            if (map.has(key) && map.get(key).size < utilNum) {
              if (!(map.get(key).has(key2))) {
                map.get(key).set(key2, 1)
              }
            } else {
              map.set(key, new Map())
              map.get(key).set(key2, 1)
            }
          })
          tmp.allCanSelectNum = 0
          map.forEach(function(val, key) {
            tmp.allCanSelectNum += val.size
          })
          all += tmp.allCanSelectNum
        }
      } else if (floorOpen) {
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const map = new Map()
          const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
          tmp.mediaPointList.forEach(item => {
            const key = (item.building_number != null ? item.building_number + '号楼' : '') + (item.unit_number != null ? item.unit_number + '单元' : '') + (item.floor != null ? item.floor + '层' : '')
            if (!map.has(key)) {
              map.set(key, 1)
            }
          })
          tmp.allCanSelectNum = map.size
          all += tmp.allCanSelectNum
        }
      } else if (utilOpen) {
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const map = new Map()
          const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
          tmp.mediaPointList.forEach(item => {
            const key = (item.building_number != null ? item.building_number + '号楼' : '') + (item.unit_number != null ? item.unit_number + '单元' : '')
            if (map.has(key)) {
              if (map.get(key) < utilNum) {
                map.set(key, map.get(key) + 1)
              }
            } else {
              map.set(key, 1)
            }
          })
          tmp.allCanSelectNum = 0
          map.forEach(function(val, key) {
            tmp.allCanSelectNum += val
          })
          all += tmp.allCanSelectNum
        }
      } else {
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
          tmp.allCanSelectNum = tmp.point_type_count
          all += tmp.point_type_count
        }
      }
      this.selectPointArr.forEach(item => {
        if (item.id == typeId) {
          item.count = all
        }
      })
    },
    /**
     * 开启综合市场过滤
     */
    openMarket(val) {
      const typeId = 9
      this.openRuleFilter()
      if (val) {
        this.marketOpenFilter(typeId, this.rule_filter.market_num)
      } else {
        this.marketCloseFilter(typeId)
      }
    },
    /**
     * 综合市场输入框事件
     */
    marketInputChange(val) {
      const typeId = 9
      this.openRuleFilter()
      if (this.rule_filter.open_market) {
        this.marketOpenFilter(typeId, val)
      }
    },
    /**
     * 综合市场过滤
     * @param typeId
     * @param num
     */
    marketOpenFilter(typeId, num) {
      let all = 0
      for (let i = 0; i < this.buildingTableData.length; i++) {
        const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
        let total = 0
        total += tmp.mediaPointList.length > num ? num : tmp.mediaPointList.length
        tmp.allCanSelectNum = total
        all += total
      }
      this.selectPointArr.forEach(item => {
        if (item.id == typeId) {
          item.count = all
        }
      })
    },
    /**
     * 综合市场开启事件
     * @param typeId
     */
    marketCloseFilter(typeId) {
      let all = 0
      for (let i = 0; i < this.buildingTableData.length; i++) {
        const tmp = this.buildingTableData[i].pointTypeCountVOMap[typeId]
        tmp.allCanSelectNum = tmp.point_type_count
        all += tmp.point_type_count
      }
      this.selectPointArr.forEach(item => {
        if (item.id == typeId) {
          item.count = all
        }
      })
    },
    /**
     * 表格输入框change事件 需要改变点位选中状态
     * @param row
     * @param num
     * @param pointTypeId
     */
    tableInputChange(row, num, pointTypeId, isQuickSelection = false, ruleArr = []) {
      if (num <= 0) {
        var data = row.pointTypeCountVOMap[pointTypeId].mediaPointList
        for (let i = data.length - 1; i >= 0; i--) {
          if (data[i].checked && num != 0) {
            num++
            data[i].checked = !data[i].checked
          }
        }
      }
      var data = row.pointTypeCountVOMap[pointTypeId].mediaPointList
      var newData = {}
      // 如果是电梯智能框 格式化数据
      if (pointTypeId == 1 && (this.rule_filter.open_floor || this.rule_filter.open_residential_quarters)) {
        if (this.rule_filter.open_floor && this.rule_filter.open_residential_quarters) {
          for (let i = 0; i < data.length; i++) {
            var temp = data[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '')
            if (!(key in newData)) {
              this.$set(newData, key, {})
            }
            const key2 = (temp.floor != null ? temp.floor + '层' : '')
            if (!(key2 in newData[key])) {
              this.$set(newData[key], key2, [])
            }
            newData[key][key2].push(temp)
          }
        } else if (this.rule_filter.open_residential_quarters) {
          for (let i = 0; i < data.length; i++) {
            var temp = data[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '')
            if (!(key in newData)) {
              this.$set(newData, key, [])
            }
            newData[key].push(temp)
          }
        } else if (this.rule_filter.open_floor) {
          for (let i = 0; i < data.length; i++) {
            var temp = data[i]
            const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '') + (temp.floor != null ? temp.floor + '层' : '')
            if (!(key in newData)) {
              this.$set(newData, key, [])
            }
            newData[key].push(temp)
          }
        }
      } else {
        newData = []
        data.forEach(item => {
          newData.push(item)
        })
      }
      this.autoSelectPoint(newData, num, pointTypeId, isQuickSelection, ruleArr)
    },
    /**
     * 自动选位
     * @param newData
     * @param num
     * @param pointId
     */
    autoSelectPoint(newData, num, pointId, isQuickSelection = false, ruleArr = []) {
      if (Array.isArray(newData)) {
        newData.forEach(item => {
          if (num != 0 && !(item.checked)) {
            if (this.itemChange(pointId, item, newData, null, true, null, null, isQuickSelection, ruleArr)) {
              num--
            }
          }
        })
      } else {
        for (const key in newData) {
          if (Array.isArray(newData[key])) {
            newData[key].forEach(item => {
              if (num != 0 && !(item.checked)) {
                if (this.itemChange(pointId, item, newData[key], null, true, null, null, isQuickSelection, ruleArr)) {
                  num--
                }
              }
            })
          } else {
            for (const key2 in newData[key]) {
              newData[key][key2].forEach(item => {
                if (num != 0 && !(item.checked)) {
                  if (this.itemChange(pointId, item, newData[key][key2], newData[key], true, null, null, isQuickSelection, ruleArr)) {
                    num--
                  }
                }
              })
            }
          }
        }
      }
    },
    /**
     * 取消全选
     * @param newData
     */
    cancelALlPoint(newData, pointId) {
      if (Array.isArray(newData)) {
        newData.forEach(item => {
          if (item.checked) {
            this.itemChange(pointId, item, newData, null, true)
          }
        })
      } else {
        for (const key in newData) {
          if (Array.isArray(newData[key])) {
            newData[key].forEach(item => {
              if (item.checked) {
                this.itemChange(pointId, item, newData, null, true)
              }
            })
          } else {
            for (const key2 in newData[key]) {
              newData[key][key2].forEach(item => {
                if (item.checked) {
                  this.itemChange(pointId, item, newData[key][key2], newData[key], true)
                }
              })
            }
          }
        }
      }
    },
    /**
     * 全选按钮点击事件
     * @param val
     * @param data
     * @param num
     */
    allSelectCheckBox(val, data, num, pointId) {
      if (val) {
        this.autoSelectPoint(data, num, pointId)
      } else {
        this.cancelALlPoint(data, pointId)
      }
    },
    /**
     * 点位分配输入框change事件 需要改变点位选中状态
     * @param val
     * @param pointTypeId
     * @param item
     */
    pointAllocationInputChange(val, pointTypeId, item) {
      const map = this.buildingDistribution(pointTypeId, val)
      for (let i = 0; i < this.buildingTableData.length; i++) {
        if (map.has(this.buildingTableData[i].id)) {
          const obj = map.get(this.buildingTableData[i].id)
          this.tableInputChange(this.buildingTableData[i], obj.distributionNum, pointTypeId)
        }
      }
    },
    // 清楚所有实际选中数
    clearActualNum() {
      this.selectPointArr.forEach(item => item.actual_num = 0)
    },
    // 计算每个楼盘平均分配数
    buildingDistribution(pointTypeId, num) {
      let actualDistributionNum = num
      let surplusNum = 0
      const map = new Map()
      for (let i = 0; i < this.buildingTableData.length; i++) {
        var tmp = this.buildingTableData[i].pointTypeCountVOMap[pointTypeId]
        if (tmp.to > 0) {
          actualDistributionNum -= tmp.to
        }
        if (tmp.allCanSelectNum - tmp.to > 0) {
          surplusNum += (tmp.allCanSelectNum - tmp.to)
          map.set(this.buildingTableData[i].id, {
            allNum: tmp.allCanSelectNum - tmp.to, // 总共可分配数
            distributionNum: 0, // 应该分配数
            alreadyDistributionNum: tmp.to // 已经分配数
          })
        }
      }
      // 循环计算每个楼盘的分配数
      while (actualDistributionNum > 0 && surplusNum > 0) {
        map.forEach(function(value, key) {
          if (actualDistributionNum > 0) {
            if (value.alreadyDistributionNum > 0) {
              value.alreadyDistributionNum -= 1
            } else if (value.allNum > 0) {
              value.distributionNum += 1
              value.allNum -= 1
              actualDistributionNum--
              surplusNum--
            }
          }
        })
      }
      return map
    },
    // 关闭选点弹窗
    closePointSelectionDialog() {
      this.dialogQuickSelection = {
        floorList: [],
        surfaceList: []
      }
    },
    // 显示精准选点弹窗
    showPointDetail(data, id, typeId, need_select_count = null) {
      if (this.searchForm.abType == 'AB') {
        this.ruleArr.push({ id: 4, num: 1 })
      }
      this.tmpPointDataList = data.mediaPointList
      this.precisePointSelectionDialogVisible = true
      this.clickMediaTypeId = typeId
      if (this.isCombo == 0) {
        this.allCanSelectNum = data.to
      } else {
        this.allCanSelectNum = data.allCanSelectNum
      }
      this.need_select_count = (need_select_count === null ? 0 : need_select_count)
      // this.pointDialogData.isAllSelect = false
      // this.pointDialogData.need_select_count = need_select_count
      // this.pointDialogData.id = id
      // this.pointDialogData.point_type_id = data.point_type_id
      // this.pointDialogData.point_checked_count = data.to
      // this.pointDialogData.point_type_count = data.point_type_count
      // if (this.isCombo == 1) {
      //   this.pointDialogData.point_count = data.allCanSelectNum
      // } else {
      //   this.pointDialogData.point_count = need_select_count
      // }
      // this.pointDialogData.selectAllArr = []
      // this.pointDialogData.mediaPointList = []
      // this.mediaPointList = []
      // // 如果是电梯智能框 格式化数据
      // if (typeId == 1 && (this.rule_filter.open_floor || this.rule_filter.open_residential_quarters)) {
      //   if (this.rule_filter.open_floor && this.rule_filter.open_residential_quarters) {
      //     this.pointDialogData.mediaPointData = {}
      //     for (let i = 0; i < data.mediaPointList.length; i++) {
      //       var temp = data.mediaPointList[i]
      //       const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '')
      //       if (!(key in this.pointDialogData.mediaPointData)) {
      //         this.$set(this.pointDialogData.mediaPointData, key, {})
      //       }
      //       const key2 = (temp.floor != null ? temp.floor + '层' : '')
      //       if (!(key2 in this.pointDialogData.mediaPointData[key])) {
      //         this.$set(this.pointDialogData.mediaPointData[key], key2, [])
      //       }
      //       let assign = Object.assign({}, temp)
      //       this.pointDialogData.mediaPointList.push(assign)
      //       this.pointDialogData.mediaPointData[key][key2].push(assign)
      //       if (temp.checked) {
      //         this.pointDialogData.selectAllArr.push(temp.id)
      //       }
      //     }
      //   } else if (this.rule_filter.open_residential_quarters) {
      //     this.pointDialogData.mediaPointData = {}
      //     for (let i = 0; i < data.mediaPointList.length; i++) {
      //       var temp = data.mediaPointList[i]
      //       const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '')
      //       if (!(key in this.pointDialogData.mediaPointData)) {
      //         this.$set(this.pointDialogData.mediaPointData, key, [])
      //       }
      //       let assign = Object.assign({}, temp)
      //       this.pointDialogData.mediaPointList.push(assign)
      //       this.pointDialogData.mediaPointData[key].push(assign)
      //       if (temp.checked) {
      //         this.pointDialogData.selectAllArr.push(temp.id)
      //       }
      //     }
      //   } else if (this.rule_filter.open_floor) {
      //     this.pointDialogData.mediaPointData = {}
      //     for (let i = 0; i < data.mediaPointList.length; i++) {
      //       var temp = data.mediaPointList[i]
      //       const key = (temp.building_number != null ? temp.building_number + '号楼' : '') + (temp.unit_number != null ? temp.unit_number + '单元' : '') + (temp.floor != null ? temp.floor + '层' : '')
      //       if (!(key in this.pointDialogData.mediaPointData)) {
      //         this.$set(this.pointDialogData.mediaPointData, key, [])
      //       }
      //       let assign = Object.assign({}, temp)
      //       this.pointDialogData.mediaPointList.push(assign)
      //       this.pointDialogData.mediaPointData[key].push(assign)
      //       if (temp.checked) {
      //         this.pointDialogData.selectAllArr.push(temp.id)
      //       }
      //     }
      //   }
      // } else {
      //   this.pointDialogData.mediaPointData = []
      //   data.mediaPointList.forEach(item => {
      //     let assign = Object.assign({}, item)
      //     this.pointDialogData.mediaPointList.push(assign)
      //     this.pointDialogData.mediaPointData.push(assign)
      //     if (item.checked) {
      //       this.pointDialogData.selectAllArr.push(item.id)
      //     }
      //   })
      // }
      // this.pointSelectionDialogVisible = true
    },
    /**
     * 保存选中的点位
     */
    saveSelectPoint(ids) {
      this.tmpPointDataList.forEach(point => {
        if (ids.find(id => id == point.id) === undefined) {
          point.checked = false
        } else {
          point.checked = true
        }
      })
    },
    /**
     * 点位点击事件
     * @param pointId 点位类型ID
     * @param item 点击的点位信息
     * @param arr 点击点位所在的数据信息
     * @param utilArr 当同时开启楼层和单元过滤的单元点位信息
     * @param type 是否是点击触发
     * @param max_num
     * @param selectnum
     */
    itemChange(pointId, item, arr, utilArr, type = false, max_num, selectnum, isQuickSelection = false, ruleArr = []) {
      if (this.isCombo == 0) {
        if (!(item.checked) && max_num <= selectnum) {
          if (!type) {
            this.$message.error('套餐类型不能增加点位')
            return
          }
        }
      }
      let flag = false
      // 如果是电梯智能框并开启了规则过滤
      if (pointId == 1 && (this.rule_filter.open_floor || this.rule_filter.open_residential_quarters)) {
        if (isQuickSelection) {
          if (ruleArr.find(rule => rule == item.floor) != undefined) {
            let total = this.rule_filter.residential_quarters_num
            // 同时开启
            if (this.rule_filter.open_floor && this.rule_filter.open_residential_quarters) {
              for (const key in utilArr) {
                for (let i = 0; i < utilArr[key].length; i++) {
                  if (total == 0) {
                    break
                  }
                  const tmp = utilArr[key][i]
                  if (tmp.checked) {
                    total--
                  }
                }
              }
              let f = false
              for (let i = 0; i < arr.length; i++) {
                const tmp = arr[i]
                if (tmp.checked) {
                  f = true
                  break
                }
              }
              if (!(f) && total > 0) {
                flag = true
              }
            } else if (this.rule_filter.open_floor) { // 开启楼层过滤
              let f = false
              for (let i = 0; i < arr.length; i++) {
                const tmp = arr[i]
                if (tmp.checked) {
                  f = true
                  break
                }
              }
              if (!f) {
                flag = true
              }
            } else if (this.rule_filter.open_residential_quarters) { // 开启单元过滤
              for (let i = 0; i < arr.length; i++) {
                if (total == 0) {
                  break
                }
                const tmp = arr[i]
                if (tmp.checked) {
                  total--
                }
              }
              if (total > 0) {
                flag = true
              }
            }
          }
        } else {
          let total = this.rule_filter.residential_quarters_num
          // 同时开启
          if (this.rule_filter.open_floor && this.rule_filter.open_residential_quarters) {
            for (const key in utilArr) {
              for (let i = 0; i < utilArr[key].length; i++) {
                if (total == 0) {
                  break
                }
                const tmp = utilArr[key][i]
                if (tmp.checked) {
                  total--
                }
              }
            }
            let f = false
            for (let i = 0; i < arr.length; i++) {
              const tmp = arr[i]
              if (tmp.checked) {
                f = true
                break
              }
            }
            if (!(f) && total > 0) {
              flag = true
            }
          } else if (this.rule_filter.open_floor) { // 开启楼层过滤
            let f = false
            for (let i = 0; i < arr.length; i++) {
              const tmp = arr[i]
              if (tmp.checked) {
                f = true
                break
              }
            }
            if (!f) {
              flag = true
            }
          } else if (this.rule_filter.open_residential_quarters) { // 开启单元过滤
            for (let i = 0; i < arr.length; i++) {
              if (total == 0) {
                break
              }
              const tmp = arr[i]
              if (tmp.checked) {
                total--
              }
            }
            if (total > 0) {
              flag = true
            }
          }
        }
      } else if (pointId == 9 && this.rule_filter.open_market) { // 开启综合市场过滤
        if (isQuickSelection) {
          if (ruleArr.find(rule => rule == item.ab_type_id) != undefined) {
            let total = this.rule_filter.market_num
            for (let i = 0; i < arr.length; i++) {
              if (total == 0) {
                break
              }
              const tmp = arr[i]
              if (tmp.checked) {
                total--
              }
            }
            if (total > 0) {
              flag = true
            }
          }
        } else {
          let total = this.rule_filter.market_num
          for (let i = 0; i < arr.length; i++) {
            if (total == 0) {
              break
            }
            const tmp = arr[i]
            if (tmp.checked) {
              total--
            }
          }
          if (total > 0) {
            flag = true
          }
        }
      } else {
        if (isQuickSelection) {
          if (ruleArr.find(rule => rule == item.ab_type_id) != undefined || ruleArr.find(rule => rule == item.floor) != undefined) {
            flag = true
          }
        } else {
          flag = true
        }
      }
      if (item.checked) {
        this.pointDialogData.point_checked_count -= 1
        item.checked = !item.checked
        this.pointDialogData.selectAllArr = this.pointDialogData.selectAllArr.filter(t => t != item.id)
        // 如果是综合市场并且开启了AB面规则
        if (pointId == 9 && this.searchForm.abType == 'AB') {
          let find = arr.find(tmp => tmp.id == item.pair_media_id)
          if (find) {
            find.checked = false
            if (!type) {
              this.pointDialogData.point_checked_count -= 1
              this.pointDialogData.selectAllArr = this.pointDialogData.selectAllArr.filter(t => t != find.id)
            }
          }
        }
      } else {
        if (flag) {
          this.pointDialogData.point_checked_count += 1
          item.checked = !item.checked
          this.pointDialogData.selectAllArr.push(item.id)
          if (pointId == 9 && this.searchForm.abType == 'AB') {
            let find = arr.find(tmp => tmp.id == item.pair_media_id)
            if (find) {
              find.checked = true
              if (!type) {
                this.pointDialogData.point_checked_count += 1
                this.pointDialogData.selectAllArr.push(find.id)
              }
            }
          }
          return true
        } else {
          if (!type) {
            this.$message.error('超出规则限制')
          }
        }
      }
    },
    // 精准选点确定方法
    pointDialogConfirm() {
      if (this.isCombo == 0) {
        if (this.pointDialogData.point_count != this.pointDialogData.point_checked_count) {
          this.$message.error('必须选择' + this.pointDialogData.point_count + '个点位')
          return
        }
      }
      for (let i = 0; i < this.buildingTableData.length; i++) {
        if (this.buildingTableData[i].id == this.pointDialogData.id) {
          var tmp = this.buildingTableData[i].pointTypeCountVOMap[this.pointDialogData.point_type_id].mediaPointList
          for (let j = 0; j < tmp.length; j++) {
            if (this.pointDialogData.selectAllArr.find(t => t == tmp[j].id) == undefined) {
              tmp[j].checked = false
            } else {
              tmp[j].checked = true
            }
          }
        }
      }
      this.pointSelectionDialogVisible = false
    },
    // 确认按钮点击事件
    addConfig() {
      // 检查是否有未分配的点位
      if (this.check()) {
        const type = this.isCombo
        const date = []
        this.dateRange.forEach(item => {
          date.push(item)
        })
        const arr = []
        if (this.isCombo) {
          this.selectPointArr.filter(item => item.actual_num > 0).forEach(item => {
            arr.push(item.id)
          }) // 所选择的点位类型数组
        } else {
          this.comboPointTypeArr.forEach(item => {
            arr.push(item.id)
          })
        }
        const dataArr = []
        for (let i = 0; i < this.buildingTableData.length; i++) {
          const temp = this.buildingTableData[i]
          const tmp = {}
          tmp.id = temp.id
          tmp.name = temp.name
          tmp.address = temp.address
          tmp.pointTypeCountVOMap = {}
          tmp.comboCountInfoList = temp.comboCountInfoList
          let flag = false
          for (let j = 0; j < arr.length; j++) {
            if (temp.pointTypeCountVOMap[arr[j]].to > 0) {
              flag = true
            }
            const tmpArr = []
            temp.pointTypeCountVOMap[arr[j]].mediaPointList.forEach(item => {
              tmpArr.push(Object.assign({}, item))
            })
            tmp.pointTypeCountVOMap[arr[j]] = Object.assign({}, temp.pointTypeCountVOMap[arr[j]])
            tmp.pointTypeCountVOMap[arr[j]].mediaPointList = tmpArr
          }
          if (flag) {
            dataArr.push(tmp)
          }
        }
        if (dataArr.length == 0) {
          this.$message({
            message: '请勿提交无效的配置',
            type: 'warning'
          })
          return
        }
        let res = {}
        if (this.responseType === 2) {
          res = { type, arr, date, dataArr }
        } else {
          // 整理出市场单使用的数据结构
          res = []
          arr.forEach(item => {
            let obj = {}
            obj.id = item
            obj.name = this.getPointTypeName(item)
            obj.list = []
            let map = new Map()
            dataArr.forEach(building => {
              if (building.pointTypeCountVOMap[item]) {
                let filter = building.pointTypeCountVOMap[item].mediaPointList.filter(point => point.checked === true)
                filter.forEach(point => {
                  let key = ''
                  if (item == 9) {// 如果是综和市场类型
                    key = building.name + '_' + point.media_type_spec
                  } else { // 如果是其他类型
                    key = point.media_type_spec
                  }
                  if (map.has(key)) {
                    let tmp = map.get(key)
                    tmp.count += 1
                  } else {
                    let tmp = {
                      name: item == 9 ? building.name : '',
                      media_type_id: item,
                      media_type: obj.name,
                      size_width: point.size_width,
                      size_height: point.size_height,
                      media_type_spec: point.media_type_spec,
                      media_pic_type_id: point.media_pic_type_id,
                      media_pic_type: point.media_pic_type,
                      count: 1
                    }
                    map.set(key, tmp)
                  }
                })
              }
            })
            map.forEach((value) => {
              obj.list.push(value)
            })
            res.push(obj)
          })
        }
        this.dialogShow = false
        this.$emit('save', res)
      } else {
        if (this.isCombo) {
          this.$message.error('请将点位分配完')
        } else {
          this.$message.error('请将套餐分配完')
        }
      }
    },
    check() {
      let flag = true
      if (this.isCombo == 1) {
        this.selectPointArr.forEach(item => {
          if (item.unassignedNum != 0) {
            flag = false
          }
        })
      } else {
        this.comboSum.forEach(item => {
          if (item.noDistributeNum != 0) {
            flag = false
          }
        })
      }
      return flag
    },

    closeConfigDialog() {
      this.buildingTableData = []
      this.selectPointArr = []
      this.searchForm = {
        beginDate: null,
        endDate: null,
        pcaList: [], // 行政规划
        address: null, // 地址
        positionRadius: 1000,
        buildingList: [], // 选中的楼盘信息
        buildingRadiation: false, // 楼盘是否辐射
        buildingRadius: 1000, // 楼盘辐射距离
        prohibitIndustryId: null, // 禁投行业
        pointTypeIdList: [],
        floorList: [],
        abType: 'ALL',
        type: 1,
        exclude_media_id_list: [],
        exclude_building_id_list: [],
        positionLocationList: []
      }
      this.isCombo = 2
      for (const key in this.selectBuildingMap) {
        this.selectBuildingMap [key] = []
      }
      this.show = true
      this.firstSearch = false
    },
    /**
     * 关闭事件
     */
    beforeClose() {
      this.dialogShow = false
      this.$emit('close')
    },
    showDialog() {
      this.$refs['searchForm'].clearValidate()
    },
    /**
     * 套餐和点位切换
     * @param val
     */
    typeChange(val, flag = true) {
      if (flag) {
        this.pointTypeProject.forEach(type => {
          this.selectBuildingMap[type.id] = []
        })
        this.comboTypeProject.forEach(type => {
          this.selectBuildingMap[type.id] = []
        })
        if (val) {
          this.searchForm.pointTypeIdList = []
        } else {
          this.searchForm.pointTypeIdList = this.comboPointTypeArr.map(i => {
            return i.id
          })
        }
      }
    },
    /**
     * 获取套餐详情
     */
    initComboDetail() {
      combo_info().then(res => {
        this.comboInfoList = res.data
        this.comboInfoList.forEach(item => {
          for (let i = 0; i < item.ruleList.length; i++) {
            item.ruleList[i].level = i + 1
          }
          item.ruleList.sort(function(a, b) {
            return a.level - b.level
          })
        })
      })
    },
    /**
     * 修改楼盘的套餐数据
     * [
     *   {
     *     combo_id:套餐ID
     *     rule_id:组合ID
     *     name:XX套餐-XX组合
     *     pointDataMap:{
     *       5:{ // 点位类型为key
     *         need_num:2, 组合所需要的数量
     *         total_num:2 点位可用数的总量
     *       }
     *     }
     *     distribution_num:分配数
     *   }
     * ]
     */
    showBuildingCombo(row) {
      const that = this
      let tmpArr = []
      this.comboInfoList.forEach(function(value, index) {
          value.ruleList.forEach(function(item, i) {
            let comboData = {}
            comboData.combo_id = value.combo_id
            comboData.rule_id = item.rule_id
            comboData.name = String.fromCharCode(index + 65) + '套餐' + '——' + String.fromCharCode(i + 65) + '组合'
            comboData.pointDataMap = {}
            that.comboPointTypeArr.forEach(point => {
              comboData.pointDataMap[point.id] = {
                need_num: 0,
                total_num: 0
              }
            })
            // 加入必须分配数
            item.mediaType2CountList.forEach(point => {
              comboData.pointDataMap[point.media_type_id].need_num = point.count
            })
            tmpArr.push(comboData)
          })
        }
      )
      // 处理套餐分配数
      row.comboCountInfoList.forEach(item => {
        item.ruleList.forEach(i => {
          tmpArr.forEach(combo => {
            if (combo.combo_id == i.combo_id && combo.rule_id == i.rule_id) {
              combo.distribution_num = i.count
            }
          })
        })
      })
      // 点位总数
      for (let key in row.pointTypeCountVOMap) {
        tmpArr.forEach(combo => {
          combo.pointDataMap[key].total_num = row.pointTypeCountVOMap[key].point_type_count
        })
      }
      this.combo_data_list = tmpArr.map(item => {
        return Object.assign({}, item)
      })
      this.comboDialogTmpBuildingId = row.id
      this.comboDialogTmpBuildingName = row.name
      this.comboDistributeDialogShow = true
    },
    closeComboDialog() {
      this.comboDistributeDialogShow = false
      this.comboDialogTmpBuildingId = null
    },
    /**
     * 修改楼盘套餐数量
     * @param comboDataList
     * @param use_count_map
     */
    editBuildingCombo(comboDataList, use_count_map) {
      let buildingData = this.buildingTableData.find(item => item.id == this.comboDialogTmpBuildingId)
      comboDataList.forEach(combo => {
        // 改变组合的数字
        buildingData.comboCountInfoList.forEach(item => {
          item.ruleList.forEach(rule => {
            if (combo.combo_id == rule.combo_id && combo.rule_id == rule.rule_id) {
              rule.count = combo.distribution_num
            }
          })
        })
      })
      // 根据数量改变点位状态
      let keys = use_count_map.keys()
      for (const key of keys) {
        let point = buildingData.pointTypeCountVOMap[key]
        let num = use_count_map.get(key) - point.to
        if (num > 0) {
          point.mediaPointList.forEach(item => {
            if (num > 0 && !item.checked) {
              item.checked = true
              num--
            }
          })
        } else {
          for (let i = point.mediaPointList.length - 1; i >= 0; i--) {
            if (num < 0 && point.mediaPointList[i].checked) {
              point.mediaPointList[i].checked = false
              num++
            }
          }
        }
      }
      this.closeComboDialog()
    },
    /**
     * 自动分配套餐
     */
    autoDistributionCombo(combo_id, val, oldVal) {
      if (isNaN(val)) {
        return
      }
      let map = new Map()
      let actual_num = val
      for (let i = 0; i < this.buildingTableData.length; i++) {
        // 获取楼盘套餐已经分配数
        if (!map.has(this.buildingTableData[i].id)) {
          this.buildingTableData[i].comboCountInfoList.forEach(item => {
            if (item.id == combo_id) {
              map.set(this.buildingTableData[i].id, item.count)
              actual_num -= item.count
            }
          })
        }
      }
      if (actual_num > 0) {
        let rule_arr = this.comboInfoList.find(item => item.combo_id == combo_id).ruleList
        // 根据优先级分配套餐
        rule_arr.forEach(rule => {
          let need_point = new Map()
          rule.mediaType2CountList.forEach(point => {
            need_point.set(point.media_type_id, point.count)
          })
          let can = true // 是否还能继续分配
          while (can && actual_num > 0) {
            let flag = false
            for (let i = 0; i < this.buildingTableData.length; i++) {
              // 获取楼盘套餐已经分配数
              if (!map.has(this.buildingTableData[i].id)) {
                this.buildingTableData[i].comboCountInfoList.forEach(item => {
                  if (item.id == combo_id) {
                    map.set(this.buildingTableData[i].id, item.count)
                  }
                })
              }
              // 楼盘已经分配了，暂时不给这个楼盘分配
              if (map.get(this.buildingTableData[i].id) > 0) {
                map.set(this.buildingTableData[i].id, map.get(this.buildingTableData[i].id) - 1)
                flag = true
              } else {
                if (actual_num > 0 && this.allocationByRule(need_point, this.buildingTableData[i], combo_id, rule.rule_id)) {
                  actual_num--
                  flag = true
                }
              }
            }
            if (!flag) {
              can = false
            }
          }
        })
      }
    },
    /**
     * 根据规则分配
     * @param ruleMap
     * @param buildingData
     * @param combo_id
     * @param rule_id
     * @returns {boolean}
     */
    allocationByRule(ruleMap, buildingData, combo_id, rule_id) {
      let keys = ruleMap.keys()
      let flag = true// 默认可以分配
      // 检查点位是否够用
      ruleMap.forEach(function(val, key) {
        let number = buildingData.pointTypeCountVOMap[key].point_type_count - buildingData.pointTypeCountVOMap[key].to
        if (number < val) {
          flag = false
        }
      })
      if (flag) { // 进行分配
        let combo = buildingData.comboCountInfoList.find(item => item.id == combo_id)
        let rule = combo.ruleList.find(item => item.rule_id == rule_id)
        rule.count++
        // 改变点位选中状态
        for (let key of keys) { // 检查点位是否够用
          let num = ruleMap.get(key)
          buildingData.pointTypeCountVOMap[key].to += num
          for (let i = 0; i < buildingData.pointTypeCountVOMap[key].mediaPointList.length; i++) {
            let point = buildingData.pointTypeCountVOMap[key].mediaPointList[i]
            if (!point.checked && num > 0) {
              point.checked = true
              num--
            }
          }
        }
      }
      return flag
    },
    floorQuickSelection(val, all = false) {
      if (all) {
        this.buildingTableData.forEach(item => {
          let count = 0
          let mediaPointList = item.pointTypeCountVOMap[1].mediaPointList
          mediaPointList.forEach(point => {
            if (val.includes(parseInt(point.floor))) {
              count++
            }
          })
          this.tableInputChange(item, count, 1, true, val)
        })
      } else {
        let count = 0
        let mediaPointList = this.pointDialogData.mediaPointList
        const tmpRow = {}
        tmpRow.pointTypeCountVOMap = { 1: {} }
        tmpRow.pointTypeCountVOMap[1].mediaPointList = mediaPointList
        mediaPointList.forEach(point => {
          if (val.includes(parseInt(point.floor))) {
            count++
          }
        })
        this.tableInputChange(tmpRow, count, 1, true, val)
      }
    },
    surfaceQuickSelection(val, all = false) {
      if (all) {
        this.buildingTableData.forEach(item => {
          let count = 0
          let mediaPointList = item.pointTypeCountVOMap[9].mediaPointList
          mediaPointList.forEach(point => {
            if (val.includes(point.ab_type_id)) {
              count++
            }
          })
          this.tableInputChange(item, count, 9, true, val)
        })
      } else {
        let count = 0
        let mediaPointList = this.pointDialogData.mediaPointList
        const tmpRow = {}
        tmpRow.pointTypeCountVOMap = { 9: {} }
        tmpRow.pointTypeCountVOMap[9].mediaPointList = mediaPointList
        mediaPointList.forEach(point => {
          if (val.includes(point.ab_type_id)) {
            count++
          }
        })
        this.tableInputChange(tmpRow, count, 9, true, val)
      }
    },
    closePrecisePointSelectionDialog() {
      this.precisePointSelectionDialogVisible = false
      this.tmpPointDataList = []
    },
    downloadExcel() {
      getBuildingImportExcel()
    },
    beforeAvatarUpload() {
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    success(res) {
      if (res.code === 200) {
        res.data.forEach(id => {
          if (this.buildingList.find(item => item == id) === undefined) {
            this.buildingList.push(id)
          }
        })
      } else {
        this.$message.error('操作失败')
      }
      this.loading.close()
    },
    error() {
      this.$message.error('操作失败')
      this.loading.close()
    }
  },
  watch: {
    buildingTableData: {
      handler(newVal, oldVal) { // 当数据改变计算实际选中总数和未分配数
        if (this.isCombo == 1) {
          this.clearActualNum()
          for (let i = 0; i < newVal.length; i++) {
            const tmp = newVal[i].pointTypeCountVOMap
            for (const tmpKey in tmp) {
              var count = 0
              for (let j = 0; j < tmp[tmpKey].mediaPointList.length; j++) {
                if (tmp[tmpKey].mediaPointList[j].checked) {
                  count++
                }
              }
              tmp[tmpKey].to = count
              for (let j = 0; j < this.selectPointArr.length; j++) {
                if (tmpKey == this.selectPointArr[j].id) {
                  this.selectPointArr[j].actual_num += count
                  // this.selectPointArr[j].unassignedNum = this.selectPointArr[j].num - this.selectPointArr[j].actual_num
                }
              }
            }
          }
        } else {
          newVal.forEach(building => {
            // 计算每个套餐总和
            building.comboCountInfoList.forEach(item => {
              let count = 0
              item.ruleList.forEach(rule => {
                count += rule.count
              })
              item.count = count
              let combo = this.comboSum.find(combo => combo.id == item.id)
              combo.noDistributeNum = combo.distributeNum - item.count
            })
            // 计算每个点位使用数
            for (let key in building.pointTypeCountVOMap) {
              let count = 0
              building.pointTypeCountVOMap[key].mediaPointList.forEach(point => {
                if (point.checked) {
                  count++
                }
              })
              building.pointTypeCountVOMap[key].to = count
            }
          })
        }
      },
      deep: true
    },
    'searchForm.pointTypeIdList': {
      handler(val) {
        this.pointTypeChange(val)
      }
    },
    selectPointArr: {
      handler(val) {
        val.forEach(item => item.unassignedNum = item.num - item.actual_num)
      },
      deep: true
    },
    // 点位数组
    pointTypeIdList: {
      handler(val) {
        val.forEach(item => {
          if (this.searchForm.pointTypeIdList.find(type => type == item) == undefined) {
            this.searchForm.pointTypeIdList.push(item)
          }
        })
      },
      deep: true
    },
    // 排除的楼盘数据
    excludeBuildingIdList: {
      handler(val) {
        this.searchForm.exclude_building_id_list = val
      },
      deep: true
    },
    // 排除的点位数据
    excludeMediaIdList: {
      handler(val) {
        this.searchForm.exclude_media_id_list = val
      },
      deep: true
    },
    // 楼盘数据
    buildingList: {
      handler(val) {
        val.forEach(i => {
          let source = this.buildingArr.find(item => item.id == i)
          if (source) {
            this.selectBuildingMap[source.type_id].push(Object.assign({}, source))
          }
        })
      },
      deep: true
    },
    configType: {
      handler(val) {
        this.searchForm.type = val
        this.typeChange(val, false)
      },
      immediate: true
    },
    comboSum: {
      handler(val) {
        if (this.isCombo == 0) {
          let map = new Map()
          this.buildingTableData.forEach(building => {
            // 计算每个套餐总和
            building.comboCountInfoList.forEach(item => {
              let count = 0
              item.ruleList.forEach(rule => {
                count += rule.count
              })
              if (map.has(item.id)) {
                map.set(item.id, map.get(item.id) + count)
              } else {
                map.set(item.id, count)
              }
            })
          })
          val.forEach(item => {
            if (map.has(item.id)) {
              item.noDistributeNum = item.distributeNum - map.get(item.id)
            }
          })
        }
      },
      deep: true
    },
    dateRange: {
      handler(arr) {
        if (arr.length >= 2) {
          this.searchForm.beginDate = arr[0]
          this.searchForm.endDate = arr[1]
        }
      },
      deep: true,
      immediate: true
    },
    rule_filter: {
      handler(val) {
        this.ruleArr = []
        if (val.open_residential_quarters) {
          this.ruleArr.push({
            id: 1,
            num: val.residential_quarters_num
          })
        }
        if (val.open_floor) {
          this.ruleArr.push({
            id: 2,
            num: 1
          })
        }
        if (val.open_market) {
          this.ruleArr.push({
            id: 3,
            num: val.market_num
          })
        }
      },
      deep: true
    }
  }
}
</script>

<style scoped lang="scss">
.header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-top: 10px;
}

.button_box {
  text-align: center;
}

.search_card {
  margin: 0 0 25px 0;
  border: 1px solid #ddd;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px 5px;
}

.title_card {
  position: absolute;
  background-color: #fff;
  padding: 5px 10px;
  width: 50px;
  height: 20px;
  line-height: 20px;
  left: 40px;
  top: -10px;
  font-weight: 700;
  font-size: 15px;
}

/deep/ .search_box .el-form-item {
  margin-bottom: 0;
}

/deep/ .el-divider__text {
  font-size: 16px;
  font-weight: bold
}

.address_title {
  color: #333;
  font-weight: bold;
}

/deep/ .el-divider__text {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.no-first-el-form-item {
  margin-left: 30px;
}

/deep/ .el-divider__text {
  font-weight: 700;
  font-size: 16px;
}

.rule_filter_card_box {
}

/deep/ .box-card {
  margin: 5px;
}

.rule_box {
  font-size: 13px;
}

/deep/ .table-herder {
  color: #111111 !important;
}

/deep/ .split-line {
  margin-top: 10px !important;
  margin-bottom: 0 !important;
}

.item {
  width: 70px;
  height: 70px;
  text-align: center;
  display: table;
  padding: 5px;
  margin: 10px 5px;
  border: 1px dashed #ddd;
  border-radius: 10px;
}

.checked-box {
  background-color: rgba(215, 240, 219, .8);
  border-style: solid;
}

/deep/ .quickSelectionForm .el-form-item {
  margin-bottom: 0;
}

.quick_selection_box {
  margin-left: 10px;
  display: inline-block;
}
</style>
